<?php

namespace App\Http\Controllers\Entity\pic_albums;

use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\pic_albums\pic_albumsRequest;
use App\Models\Entity\pic_albums\pic_albums;
use App\Models\Entity\pic_albums\pic_album_pics;
use App\Models\Common\EntityData\Channel\Sp;
use App\Models\Entity\Asset\Video\Media\Vposteri;
use App\Repositories\Entity\pic_albums\pic_albumsRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use DB;

class pic_albumsController extends Controller
{
    use ModelForm;

    /** @var  pic_albumsRepository */
    private $picAlbumsRepository;

    public function __construct(pic_albumsRepository $picAlbumsRepo)
    {
        $this->picAlbumsRepository = $picAlbumsRepo;
    }

    /**
     * Display a listing of the pic_albums.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.pic_albums.pic_albums.index_header'));
            $content->description(__('entity.pic_albums.pic_albums.index_description'));

            $content->body($this->grid());
            $content->row(view('entity.tag.addContentTagModal'));
        });
    }

    /**
     * Show the form for creating a new pic_albums.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.pic_albums.pic_albums.create_header'));
            $content->description(__('entity.pic_albums.pic_albums.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created pic_albums in storage.
     *
     * @param pic_albumsRequest $request
     *
     * @return Response
     */
    public function store(pic_albumsRequest $request)
    {
        $input = $request->all();

        $picAlbums = $this->picAlbumsRepository->create($input);
        //保存图集图片
        $image = $request->file('pics'); //使用laravel 自带的request类来获取一下文件.
        $this->savePic($image,$input,$picAlbums);

        Flash::success(__('entity.pic_albums.pic_albums.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.pic_albums.pic_albums.index'));

    }


    protected function savePic($images = array(),&$input,$picAlbums){

        if(empty($images)){
            return false;
        }
        foreach ($images as $image){
            if ($image) {
                if ($image->isValid()) {
                    // 允许上传的图片格式
                    $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                    if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                        return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                    }
                    $realPath = $image->getRealPath(); //临时文件的绝对路径
                    // 获得图片的扩展名
                    $extension = $image->getClientOriginalExtension();
                    // 获取上传图片的文件名
                    $imagesName = str_replace('.'.$extension, '', $image->getClientOriginalName());

                    // 重新命名上传文件名字
                    $newImageName = md5($picAlbums->id.time().$image->getClientOriginalName()). "." . $extension;

                    // 图片的完整路径
                    $fullPath = 'public'.DIRECTORY_SEPARATOR.'pic_albums'.DIRECTORY_SEPARATOR.$picAlbums->sp_id.DIRECTORY_SEPARATOR.$picAlbums->id.DIRECTORY_SEPARATOR.$newImageName;
                    $bool     = Storage::put($fullPath, file_get_contents($realPath));
                    if($bool){
                        $vposteri    = new Vposteri();
                        $data = array();
                        $data['name'] = $imagesName;
                        $data['title']    = $imagesName;
                        $data['subtitle']    = $imagesName;
                        $data['vimgtag_id']    = 3;
                        $data['imgtpl_id']    = 1;
                        $data['href']    = str_replace("\\","/",$fullPath);
                        $rs = $vposteri->create($data);
                        DB::insert('insert into pic_album_pics (pic_album_id, vposteri_id) values (?, ?)', [$picAlbums->id, $rs->id]);
                    }
                }
            }
        }
    }

    /**
     * Display the specified pic_albums.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $picAlbums = $this->picAlbumsRepository->findWithoutFail($id);

        if (empty($picAlbums)) {
            Flash::error(__('entity.pic_albums.pic_albums.not_found'));

            return redirect(route('entity.pic_albums.pic_albums.index'));
        }

        return view('entity.pic_albums.pic_albums.show')->with('picAlbums', $picAlbums);

    }

    /**
     * Show the form for editing the specified pic_albums.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.pic_albums.pic_albums.edit_header'));
            $content->description(__('entity.pic_albums.pic_albums.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified pic_albums in storage.
     *
     * @param  int              $id
     * @param pic_albumsRequest $request
     *
     * @return Response
     */
    public function update($id, pic_albumsRequest $request)
    {
        $picAlbums = $this->picAlbumsRepository->findWithoutFail($id);

        if (empty($picAlbums)) {
            Flash::error(__('entity.pic_albums.pic_albums.not_found'));

            return redirect(route('entity.pic_albums.pic_albums.index'));
        }
        $input = $request->all();

        //保存图集图片
        $image = $request->file('pics'); //使用laravel 自带的request类来获取一下文件.
        $this->savePic($image,$input,$picAlbums);

        $picAlbums = $this->picAlbumsRepository->update($input, $id);


        Flash::success(__('entity.pic_albums.pic_albums.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.pic_albums.pic_albums.index'));
    }

    /**
     * Remove the specified pic_albums from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {

        //删除关联图片
        pic_album_pics::whereIn('pic_album_id', explode(",", $id))->forceDelete();

        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->picAlbumsRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('entity.pic_albums.pic_albums.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $picAlbums = $this->picAlbumsRepository->findWithoutFail($id);

        if (empty($picAlbums)) {
            Flash::error(__('entity.pic_albums.pic_albums.not_found'));

            return redirect(route('entity.pic_albums.pic_albums.index'));
        }

        if ($flag = $this->picAlbumsRepository->delete($id)) {

            return response()->json(['message' => __('entity.pic_albums.pic_albums.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(pic_albums::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '图集名称');
            $form->textarea('description', '描述');
            $sp_ids = Sp::pluck('name', 'id');
            $form->select('sp_id', '服务商')->options($sp_ids);

            $form->number('listorder', '排序');

            // 添加删除按钮
            $form->multipleImage('pics','图片')->removable();

            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(pic_albums::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('entity.pic_albums.pic_albums.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('entity.pic_albums.pic_albums.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('entity.pic_albums.pic_albums.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('entity.pic_albums.pic_albums.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('entity.pic_albums.pic_albums.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('entity.pic_albums.pic_albums.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('entity.pic_albums.pic_albums.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.pic_albums.pic_albums.destroy')) {
                    $actions->disableDelete();
                }

                // append一个操作
                $actions->prepend('<a href="'.$actions->getKey().'/content"><i class="fa fa-list" title="图片列表"></i></a>');

                $url = route('entity.tag.selectTag', ['tag_content_id' => $actions->getKey(),'tag_content_type'=>'pic_album']);
                $actions->append('<a href="'.$url.'" data-toggle="modal"  data-target="#add-content-tag-modal" title="打标签"><i class="fa fa-paper-plane"></i></a>');

                //导入栏目
                $url = route('application.column_assets.selectColumn', ['content_id' => $actions->getKey(),'content_type'=>'3']);
                $actions->append('<a href="'.$url.'" data-toggle="modal"  data-target="#add-content-tag-modal" title="导入栏目"><i class="fa fa-download"></i></a>');

            });

            // 导出按钮
            if (Admin::user()->cannot('entity.pic_albums.pic_albums.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.pic_albums.pic_albums.batch_destroy')) {
                        $batch->disableDelete();
                    }

                    //批量打标签
                    $batch->add('打标签', new \App\Admin\Extensions\Tools\contentTag('pic_album'));

                    //批量导入栏目
                    $batch->add('导入栏目', new \App\Admin\Extensions\Tools\contentColumn('3'));
                });
            });
            $grid->column('id', '图集ID')->sortable();
            $grid->column('name', '图集名称')->sortable();
            $grid->tags('标签')->pluck('name')->label('primary');
            $grid->column('description', '描述')->sortable();
            $grid->column('sp.name', '服务商')->sortable();
            $grid->column('listorder', '排序')->sortable();



            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '图集名称');
                $filter->between('created_at', '创建时间')->datetime();

            });
        });
    }


    /*
     * 图片管理页面
     */
    public function content(Request $request,$id){
        //return response()->json(['status' => 'error', 'content' => '非法操作1']);
        $pic_albums_info = pic_albums::with(['posteris'])->find($id);
        $_GET['pic_album_id'] = $id;
        return Admin::content(function (Content $content) use ($id,$pic_albums_info) {
            $content->header(__('图集图片管理'));
            $content->description(__('图集名称【'.$pic_albums_info['name']."】 "));
            $content->body($this->picGrid($id));
        });

    }

    public function picGrid(){
        return Admin::grid(pic_album_pics::class , function (Grid $grid) {
            $grid->model()->where('pic_album_id', '=', $_GET['pic_album_id']);

            $grid->disableCreation();
            $grid->disableExport();

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                //dd( $actions->row);
                $actions->disableEdit();
                //$actions->disableDelete();
                // append一个操作
                $actions->prepend('<a href="/admin/entity/asset/video/media/vposteris/'.$actions->row->vposteri_id.'/edit"><i class="fa fa-edit" title="编辑"></i></a>');
            });

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    //$batch->disableDelete();
                });
            });

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                $filter->disableIdFilter();
            });
            $grid->column('posteris.id', '图片ID')->sortable();
            $grid->column('posteris.name', '图片名称')->sortable();
            $grid->column('posteris.title', '显示标题')->sortable();
            $grid->column('posteris.href', '图片')->image('http://picupload.cc/', 150, 150);
            $grid->column('posteris.listorder', '排序')->sortable();
        });
    }


    public function delPic(Request $request,$id,$pic_id){
        $pic_id = explode(',',$pic_id);
        $data = pic_album_pics::whereIn('id', $pic_id)->get();
        $flag = pic_album_pics::whereIn('id', $pic_id)->forceDelete();
        if ($flag) {
            return response()->json(['content' => '删除成功!', 'status' => true]);
        } else {
            return response()->json(['content' => '删除失败!', 'status' => false]);
        }

    }
}
